package algorithms.leecode;

import java.util.ArrayList;
import java.util.List;

public class Au56 {
    public static void main(String[] args) {
        int[][] ss = {
                {1,4},
                {2,6},
                {7,8},
        };
        int[][] res = merge(ss);
        System.err.println(res[0][1]);
    }
    public static int[][] merge(int[][] intervals) {
        for(int i = 0; i< intervals.length - 1;i++) {
            for(int j = 0;j < intervals.length - i - 1;j++) {
                if(intervals[j][0] > intervals[j + 1][0]) {
                    exeh(intervals,j,j + 1);
                }
            }
        }
        List<List<Integer>> lists = new ArrayList<>();
        int maxEnd = -100;
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i< intervals.length ;i++) {
            if(intervals[i][0] > maxEnd ) {
                if(maxEnd != -100) {
                    list.add(maxEnd);
                    lists.add(list);
                }
                maxEnd = intervals[i][1];


                list = new ArrayList<>();
                list.add(intervals[i][0]);
            } else {
                if(maxEnd < intervals[i][1]) {
                    maxEnd = intervals[i][1];
                }
            }

        }
        list.add(maxEnd);
        lists.add(list);
        int[][] res = new int[lists.size()][2];

        return lists.toArray(res);
    }

    public static void exeh(int[][] intervals,int x,int y) {
        int[] tmp = intervals[x];
        intervals[x] = intervals[y];
        intervals[y] = tmp;
    }
}
